﻿using MapleLeaf.Application.CookBook;
using MapleLeaf.Application.CookBook.Models;
using MapleLeaf.Core;
using MapleLeaf.Core.Cache.Redis;
using MapleLeaf.Core.Dto;
using MapleLeaf.Core.Extension;
using MapleLeaf.Model.CookBook.Organization.Entity;
using MapleLeaf.Model.CookBook.Organization.Relation;
using MapleLeaf.Service.CookBook.Models;
using MapleLeaf.WebApi.CookBook.Controllers.Paramters;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Threading.Tasks;

namespace MapleLeaf.WebApi.CookBook.Controllers.SystemManagement
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class UsersController : ApiBaseController
    {

        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public UsersController(OrganizationClient organizationClient, SystemClient systemClient)
        {
            _organizationClient = organizationClient;
            _systemClient = systemClient;
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<UserInfo> GetCurrentUserInfoAsync()
        {
            var user = AppHelper.LoginUserInfo;
            user.Perms = _systemClient.GetMenuPermissionList(user.Roles.First());
            return Success(user);
        }
        /// <summary>
        /// 获取个人资料
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<UserProfileModel>> GetUserProfile()
        {
            var user = AppHelper.LoginUserInfo;
            var model = await _organizationClient.GetUserProfileModelAsync(user.UserName!);
            return Success(model);
        }

        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<UserVo>> GetUserById(long id)
        {
            var model = await _organizationClient.GetUserByIdAsync(id);
            var roleList = await _organizationClient.GetUserRoleByUserIdAsync(id);
            var vo = model.Adapt<UserVo>();
            vo.RoleIds = roleList.ConvertAll(r => r.RoleId);
            return Success(vo);
        }

        /// <summary>
        /// 获取角色分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<PaginationModel<UserVo>>> GetUserPageList(UserPageQuery query)
        {
            var whereExp = Expressionable.Create<UserEntity>();
            whereExp.AndIF(query.DeptId > 0, p => p.DeptId == query.DeptId);
            whereExp.AndIF(!query.Keywords.IsNullOrEmpty(), p => p.UserName.Contains(query.Keywords!) ||  p.NickName. Contains(query.Keywords!));
            whereExp.AndIF(query.Status > 0, p => p.Status == query.Status);
            whereExp.AndIF(!query.CreateTime.None(), p =>  p.CreateTime >= SqlFunc.ToDate(query.CreateTime![0]) && p.CreateTime <= SqlFunc.ToDate(query.CreateTime[1]));
            var pagemodel = new PageModel()
            {
                PageIndex = query.PageIndex,
                PageSize = query.PageSize,
            };
            var list = await _organizationClient.GetUserPageListAsync(whereExp.ToExpression(), pagemodel);

            PaginationModel<UserVo> result = new()
            {
                PageIndex = query.PageIndex,
                PageSize = query.PageSize,
                Total = pagemodel.TotalCount,
                List = list
            };
            return Success(result);
        }
        /// <summary>
        /// 获取人员信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveUser(UserVo vo)
        {
            var entity = vo.Adapt<UserEntity>();
            var res = await _organizationClient.SaveUserAsync(entity);
            if (!vo.RoleIds.None())
            {
                var datas = vo.RoleIds!.Select(r => new UserRoleEntity() { UserId = entity.Id, RoleId = r }).ToList();
                var roleList = await _organizationClient.SaveUserRoleAsync(datas);
            }
            return res ? Success("保存成功") : Fail("保存失败");
        }
    }
}
